import {forEach, forIn, isArray, isEmpty, isObject} from "lodash-es";

let ins = null;

/**
 * 枚举缓存
 */
class ComboCache {

    loading = {};

    constructor() {

        if (isEmpty(!ins)) {
            return ins;
        }

        ins = this;
    }

    /**
     * 枚举缓存。
     * 以 selector 为 key，枚举数据为 value
     * @type {{}}
     */
    caches = {};

    addCache(key, value) {
        if (key) {
            this.caches[key] = value;
        }
    }

    getCache(key) {
        // if (key === 'TEST') {
        //     return [
        //         {code: '1', name: 'type1'},
        //         {code: '2', name: 'type2'},
        //         {code: '3', name: 'type3'},
        //     ]
        // }
        return this.caches[key] || [];
    }

    deleteCache(key) {
        delete this.caches[key];
    }

    resetCache(values = {}) {
        this.caches = values;
    }


    /**
     * 正在获取枚举数据的 枚举组件的实例。
     * 以 selector 为 key，以 {[combo实例的唯一标识]: combo实例} 为 value。
     * 用于在获取枚举数据之后，统一更新这些枚举组件
     * @type {{}}
     */
    loadingComboInstances = {};

    addLoadingIns(selector, insKey, ins) {
        if (!isObject(this.loadingComboInstances[selector])) {
            this.loadingComboInstances[selector] = {};
        }
        this.loadingComboInstances[selector][insKey] = ins;
    }

    removeLoadingIns(selector, insKey) {
        if(this.loadingComboInstances[selector]) {
            delete this.loadingComboInstances[selector][insKey];
        }
    }

    updateComboInstances(selector) {
        // console.log('updateComboInstances', this.loadingComboInstances);
        forEach(this.loadingComboInstances[selector], (comboIns) => {

            if (comboIns && comboIns.setState) {
                let list = this.getCache(selector);
                let newState = {loading: false};

                if (!isEmpty(list)) {
                    newState.list = list;
                }
                comboIns.setState(newState);
            }
        });
        delete this.loadingComboInstances[selector];
    }
}

export default new ComboCache();
